import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect } from "@nestjs/websockets";
import { TerminalService } from "./terminal.service";
import { Server, Socket } from 'socket.io'
import pty from 'node-pty';
@WebSocketGateway(8899, {
    transports: ['websocket'],
    cors: {
      origin: '*'
    }
})
export class TerminalWebSocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  term: null | pty.IPty;
  // roomsMap: Map<string, string>
  constructor(
    private readonly terminalService: TerminalService
  ) {
    this.term = null
    // this.roomsMap = new Map()
  }

  handleConnection(client: Socket, ...args: any[]) {
    const { pid } = client.handshake.query as Record<string, any>
    const term = this.terminalService.getTerminal(pid)
    if (term) {
      term.onData((e) => {
        client.emit('message', e);
      })
      this.term = term
    }
  }

  handleDisconnect(client: any) {
    const { pid } = client.handshake.query as Record<string, any>
    if (this.term) {
      this.term.kill()
      this.terminalService.closeTerminal(pid)
    }
  }


  // @WebSocketServer()
  // server: Server


  // 订阅hello事件
  @SubscribeMessage('hello')
  hello(@MessageBody() reqData: { name: string }) {
    console.log(JSON.stringify(reqData));
  }

  // 监听 message 事件，写入终端
  @SubscribeMessage('message')
  message(@MessageBody() req: string, @ConnectedSocket() client: Socket) {
    if (this.term) {
      this.term.write(req)
    }
  }
}
